﻿using System.IO;
using System.IO.Compression;

namespace Foundation
{
    public static class Compressor
    {
        public static void ConvertFile(string inputFileName, CompressionMode compressionMode, string outputFileName = null)
        {
            outputFileName = outputFileName ??
                             (compressionMode == CompressionMode.Compress
                                  ? inputFileName + ".compressed"
                                  : inputFileName.Replace(".compressed", string.Empty));
            var inputFileBytes = File.ReadAllBytes(inputFileName);
            ConvertBytesToFile(inputFileBytes, outputFileName, compressionMode);
        }

        public static void ConvertBytesToFile(byte[] inputFileBytes, string outputFileName, CompressionMode compressionMode = CompressionMode.Decompress)
        {
            var bytes = ConvertBytes(inputFileBytes, compressionMode);
            File.WriteAllBytes(outputFileName, bytes);
        }

        public static byte[] ConvertBytes(byte[] inputFileBytes, CompressionMode mode = CompressionMode.Decompress)
        {
            using (var inputStream = new MemoryStream(inputFileBytes))
            using (var outputStream = new MemoryStream())
            {
                if (mode == CompressionMode.Compress)
                    using (var convertStream = new GZipStream(outputStream, CompressionMode.Compress))
                        inputStream.CopyTo(convertStream);

                if (mode == CompressionMode.Decompress)
                    using (var convertStream = new GZipStream(inputStream, CompressionMode.Decompress))
                        convertStream.CopyTo(outputStream);

                var bytes = outputStream.ToArray();
                return bytes;
            }
        }
    }
}
